import { RULES, defaultPerson } from '@/const';
import type { AllFormFields, FormFields } from '@/types';
import { Form } from 'ant-design-vue';
import dayjs from 'dayjs';
import { onMounted, reactive, watchEffect } from 'vue';


export interface FormInit {
	add?: boolean;
	resetFields: () => void;
}

export const useFromInit = (props: FormInit) => {
	const { resetFields } = props;
	onMounted(() => {
		if (props.add) {
			resetFields?.();
		}
	});
};

// 表单提交
interface FormSubmit {
	validate: () => Promise<any>;
	formState: FormFields;
	// formState: any;
}
export const useSubmit = (props: FormSubmit) => {
	const { validate, formState } = props;
	return () => new Promise((resolve, reject) => {
		validate().then(() => {
			resolve(formState);
		}).catch((err: any) => {
			reject(err);
		});
	});
};

export const useOldForm = () => {
	const useForm = Form.useForm;
	const formState = reactive<AllFormFields>(structuredClone(defaultPerson));
	const { validate, validateInfos, clearValidate, resetFields } = useForm(formState, RULES);

	watchEffect(() => {
		if (formState.birth) {
			const birthYear = dayjs(formState.birth).year();
			const currentYear = dayjs().year();
			if (birthYear && birthYear < currentYear) {
				formState.age = currentYear - birthYear;
			}
		}
		if (formState.careLevel) {
			formState.packages = [];
		}
	});

	return {
		formState,
		validate,
		validateInfos,
		clearValidate,
		resetFields
	};
};

export const useCustomForm = () => {
	const formItemContext = Form.useInjectFormItemContext();
	return formItemContext
};
